<template>
  <div>
    <!-- 导航栏 -->
    <van-nav-bar title="编辑资料" left-arrow @click-left="$router.back()" />

    <!-- 头像区域 -->
    <div class="avatar-box">
      <van-image
        :src="$store.state.userInfo.photo"
        fit="cover"
        round
      ></van-image>
      <van-uploader :after-read="afterRead" />
    </div>

    <!-- 三个cell -->
    <van-cell-group>
      <van-cell
        title="名称"
        :value="$store.state.userInfo.name"
        is-link
        @click="clickNameCell"
      />
      <van-cell
        title="性别"
        :value="$store.state.userInfo.gender == 1 ? '女' : '男'"
        is-link
        @click="clickGenderCell"
      />
      <van-cell
        title="生日"
        :value="$store.state.userInfo.birthday"
        is-link
        @click="clickBirthdayCell"
      />
    </van-cell-group>
    <!-- 修改名字的地方 -->
    <!-- v-model用来控制显示或隐藏的 -->
    <van-dialog
      v-model="nameShow"
      title="修改昵称"
      show-cancel-button
      @confirm="saveName"
      @cancel="nameShow = false"
      :before-close="beforeClose"
    >
      <van-field ref="nameField" v-model="editName" class="name-field" />
    </van-dialog>
    <!-- 生日弹出层 -->
    <van-popup v-model="birthShow" position="bottom">
      <van-datetime-picker
        @confirm="saveBirthday"
        @cancel="birthShow = false"
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
      />
    </van-popup>
    <!-- 修改性别 -->
    <van-popup v-model="genderShow" position="bottom"
      ><van-picker
        show-toolbar
        title="修改性别"
        :columns="columns"
        @cancel="onCancel = genderShow = false"
        @confirm="onGenderConfirm"
        v-model="genderShow"
        :default-index="$store.state.userInfo.gender"
    /></van-popup>

    <!-- 裁剪区域 -->
    <div class="crop-box" v-show="cropShow">
      <vueCropper
        ref="cropper"
        autoCrop
        autoCropWidth="200"
        autoCropHeight="200"
        :img="cropImg"
      ></vueCropper>
      <van-button type="primary" @click="doCrop">裁剪</van-button>
      <van-button style="right: 0" type="primary" @click="cropShow = false"
        >取消</van-button
      >
    </div>
  </div>
</template>

<script>
import { editUserInfo, editPhotoAPI } from '@/api/user'
import dayjs from 'dayjs'
import { VueCropper } from 'vue-cropper'
export default {
  components: {
    VueCropper
  },
  data () {
    return {
      cropShow: false,
      cropImg: '',
      columns: ['男', '女'],
      genderShow: false,
      nameShow: false,
      editName: '',
      // 控制生日弹出层显示和隐藏
      birthShow: false,
      currentDate: new Date(),
      minDate: new Date('1949-10-1'),
      maxDate: new Date()
    }
  },
  async created () {
    this.$store.dispatch('getUserInfo')

  },
  methods: {
    //裁剪的按钮
    doCrop () {
      //调用裁剪插件获取截图的方法（得到的是file对象）
      this.$refs.cropper.getCropBlob(async (data) => {
        // console.log(data)
        //拿到文件对象就可以上传了，但是ajax上传图片必须依赖formdata
        const fm = new FormData()
        fm.append('photo', data)
        //这个时候才可以发送请求了
        const res = await editPhotoAPI(fm)
        // console.log(res.data.photo)
        //上传成功后需要修改vuex的数据
        this.$toast('修改头像成功')
        this.$store.commit('changeUserInfo', {
          ...this.$store.state.userInfo,
          photo: res.data.photo//把服务器最新修改完成的地址给photo
        })
        //然后关闭裁剪的框架
        this.cropShow = false
      })
    },
    //上传头像
    afterRead (file) {
      //显示出裁剪容器
      this.cropShow = true
      // 把选择的图片给裁剪插件
      this.cropImg = file.content

    },
    //修改性别
    async onGenderConfirm (value, index) {
      // console.log('onGenderConfirm',value,index)
      //发送请求修改服务器
      await editUserInfo({
        gender: index
      })
      //修改本地vuex数据
      this.$store.commit('changeUserInfo', {
        ...this.$store.state.userInfo,
        gender: index
      })
      //toast提示修改成功
      this.$toast('修改性别成功')
      //关闭弹窗
      this.genderShow = false
    },
    clickGenderCell () {
      this.genderShow = true
    }
    ,
    async clickNameCell () {
      this.nameShow = true
      this.editName = this.$store.state.userInfo.name
      //要等下次dom更新完毕调用
      await this.$nextTick()
      this.$refs.nameField.focus()
    },
    async saveName () {
      // console.log('first')
      //非空判断
      if (this.editName == '') return this.$toast('请输入要修改的名字')
      //调用接口修改
      await editUserInfo({
        name: this.editName
      })
      //修改服务器后，需要修改vux里面的数据
      this.$store.commit('changeUserInfo', {
        ...this.$store.state.userInfo,
        name: this.editName
      })
      //toast提示修改成功了
      this.$toast('修改成功')
      //然后就是关闭dialog
      this.nameShow = false
    },
    beforeClose (action, done) {
      done(false)
    },
    async clickBirthdayCell () {
      this.birthShow = true
      this.currentDate = new Date(this.$store.state.userInfo.birthday)
    },
    //确认修改生日
    async saveBirthday () {
      console.log('first')
      //this.currentDate是当前选中的日期对象，但是修改vuex的时候需要发送字符串，用到dayjs
      const birthday = dayjs(this.currentDate).format('YYYY-MM-DD')
      await editUserInfo({
        birthday
      })
      //修改了服务器数据还需要修改vux里面的数据
      this.$store.commit('changeUserInfo', {
        ...this.$store.state.userInfo,
        birthday
      })
      //toast提示修改成功
      this.$toast('修改生日成功')
      //关闭popup
      this.birthShow = false
    }
  }

}
</script>

<style lang="less" scoped>
.avatar-box {
  height: 140px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  .van-image {
    width: 120px;
    height: 120px;
  }
  .van-uploader {
    position: absolute;
    left: 0;
    top: 0;

    ::v-deep .van-uploader__upload {
      position: absolute;
      left: 0;
      top: 0;
      width: 100vw;
      height: 140px;
      // 能让这个东西看不见，但是它还在
      // 为什么要这么做？因为我既想要他的功能，又不想看到他
      opacity: 0;
    }
  }
}

.crop-box {
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  // background-color: red;
  .van-button {
    position: absolute;
    bottom: 0;
  }
}
</style>